import axios from "axios";
import store from "@/store";
import { canvasHolder } from "./CanvasHolder";
import { addEventListener, removeEventListener } from "./eventListener";
import {
  commonUrl,
  userName,
  passWord,
  mainWndName,
  setMaxResMemMB,
  setExpectMaxInstMemMB,
  setExpectMaxInstDrawFaceNum,
  setPageLoadLev,
} from "./config";

//预加载黑洞远程依赖资源
export async function prefetchBlackHole() {
  // 兼容黑洞那边的写法，并覆盖黑洞那边的设置
  window.serverUrl = window.location.origin + "/newblackholeapi";
  window.baseDataUrl = window.location.origin + "/newblackholeapi";
  window.imageBaseUrl = window.location.origin + "/newblackholeapi/files";
  try {
    let tpl = await getBlackHoleTPL();
    let promises = [];
    let SCRIPT_TYPE_REGEX = /<script microprefetch src=(((?!(\>|bmap|mapbox)).)*)><\/script>?/g;
    tpl.replace(SCRIPT_TYPE_REGEX, (match, configString, s2) => {
      let normalieUrl = "/blackhole/" + configString.replace(/(\"|\')/g, "");
      promises.push(loadScriptP(normalieUrl));
      return "";
    });
    Promise.all(promises).then((res) => {
      //initialSDKModule();
      store.dispatch("setStoreState", {
        BLACKhOLE_ASSETS_PREFETCH: true,
      });
    });
  } catch (error) {
    store.dispatch("setStoreState", {
      BLACKhOLE_ASSETS_PREFETCH: false,
    });
  }
}

//step2 初始化黑洞引擎系统
export function initialSDKModule() {
  //开启事件监听
  addEventListener();
  if (store.getters.blackHoleRESystemCreated) {
    return;
  }
  let canvasDom = canvasHolder.get();
  if (!canvasDom) {
    canvasDom = canvasHolder.create();
    document.body.appendChild(canvasDom);
  }

  store.dispatch("setStoreState", {
    BLACKhOLE_RELEASE_ENGINE: false,
  });

  //初始化引擎JavaScript显示组件
  window.BlackHole3D = {};
  window.BlackHole3D["canvas"] = canvasDom;

  //初始化引擎系统
  if (typeof window.BlackHole3D.RealBIMWeb === "undefined") {
    window.BlackHole3D = window.CreateBlackHoleWebSDK(window.BlackHole3D);
  } else {
    store.dispatch("setStoreState", {
      BLACKhOLE_RE_SYSTEM_READY: true,
    });
  }
}

//step3 初始化黑洞引擎场景
export function RESystemReady(width = 100, height = 100) {
  console.info("【黑洞】==>>> 引擎底层初始化完成");
  var sysInfo = new BlackHole3D.RESysInfo();
  sysInfo.workerjsPath = "./blackhole/RealBIMWeb_Worker.js";
  sysInfo.renderWidth = width;
  sysInfo.renderHieght = height;
  sysInfo.commonUrl = commonUrl;
  sysInfo.userName = userName;
  sysInfo.passWord = passWord;
  sysInfo.mainWndName = mainWndName;
  BlackHole3D.initEngineSys(sysInfo);
  BlackHole3D.Common.setUseWebCache(false);
  sessionStorage.setItem("engineLoaded", "true");
}

//step4 设置全局渲染性能控制参数
export function setupEngine() {
  // 设置全局渲染性能控制参数
  BlackHole3D.Common.setMaxResMemMB(setMaxResMemMB);
  BlackHole3D.Common.setExpectMaxInstMemMB(setExpectMaxInstMemMB);
  BlackHole3D.Common.setExpectMaxInstDrawFaceNum(setExpectMaxInstDrawFaceNum);
  BlackHole3D.Common.setPageLoadLev(setPageLoadLev);
}

//请求黑洞远程资源模板
export function getBlackHoleTPL() {
  return new Promise((resolve, reject) => {
    axios
      .get("/blackhole/index.html")
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

//卸载
export function releaseEngine() {
  removeEventListener();
  if (window.BlackHole3D) {
    BlackHole3D.Graphics.setSysPanelUIDockArea(0);
    BlackHole3D.Graphics.setGeoCoordVisible(false);
    BlackHole3D.Graphics.setViewCubeVisible(false);
    BlackHole3D.Graphics.setSysUIPanelVisible(false);
    BlackHole3D.Graphics.setSysUIColorStyle(false);
    BlackHole3D.Camera.resetCamLocate();
    BlackHole3D.Camera.resetCamBound();
    //
    BlackHole3D.Anchor.delAllAnc();
    BlackHole3D.Geometry.delAllShps();
    console.log("releaseEnginereleaseEnginereleaseEngine==releaseEngine");
  }
  if (typeof window.BlackHole3D?.releaseEngine != "undefined") {
    canvasHolder.moveCanvasToBody();
    window.BlackHole3D?.releaseEngine();
    window.BlackHole3D = null;
    store.dispatch("setStoreState", {
      BLACKhOLE_RE_SYSTEM_READY: false,
      BLACKhOLE_RE_SYSTEM_CREATED: false,
    });
  }
}

export function restEngine() {
  if (!window.BlackHole3D) {
    return;
  }
  let dom = document.getElementById("app-for-graphic");
  BlackHole3D.m_re_em_window_width = dom?.clientWidth;
  BlackHole3D.m_re_em_window_height = dom?.clientHeight;
  BlackHole3D.Graphics.setGeoCoordVisible(true);
  BlackHole3D.Graphics.setViewCubeVisible(true);
  BlackHole3D.Graphics.setSysUIPanelVisible(true);
  BlackHole3D.Graphics.setSysUIColorStyle(false);
  BlackHole3D.Graphics.setSysPanelUIDockArea(0);
  BlackHole3D.Camera.resetCamLocate();
  BlackHole3D.Camera.resetCamBound();
}

function loadScript(url, cb) {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.onload = () => {
    cb && cb();
  };
  script.src = url;
  document.querySelector("head")?.appendChild(script);
}

function loadScriptP(url) {
  return new Promise((resolve) => {
    loadScript(url, resolve);
  });
}
